package com.gxa.core.recycling.interceptor;


import com.gxa.core.recycling.anno.NeedToken;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HS
 */
@Component("permissionInterceptor")
public class PermissionInterceptor implements HandlerInterceptor {

    /**
     * 在方法执行前执行的操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        /**
         * 通过@NeedToken注解升级
         */
        //从方法中获得@NeedToken注解(通过反射获取注解信息)
        //通过强转,将object类型的handler参数转为反射可以操作的HandlerMethod(Method)

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);


        HandlerMethod method=(HandlerMethod) handler;

        boolean b = method.hasMethodAnnotation(NeedToken.class);

        if(!b){
            System.out.println("没有标记拦截");
            return true;
        }else {
            NeedToken methodAnnotation = method.getMethodAnnotation(NeedToken.class);
            boolean required = methodAnnotation.required();
            if(!required){
                System.out.println("有标记但不拦截");
                return true;
            }else {

                System.out.println("有标记拦截");
                return false;
//                String token = request.getHeader("token");
//
//                HttpSession session = request.getSession();
//                String sessionToken =  session.getAttribute("token").toString();
//
//                if (token != null && token.equals(sessionToken)) {
//                    return true;
//                } else {
//                    throw new BusinessException(ExceptionCode.WRONG_TOKEN);
//                }
            }
        }




    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在方法执行后执行的操作(指放行后)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
